<template>
    <div class="dashboard">
      <!-- 身高图表 -->
      <div ref="chart1" class="chart-item"></div>
      
      <!-- 体重/血氧/心率图表 -->
      <div ref="chart2" class="chart-item"></div>
      
      <!-- BMI/血糖图表 -->
      <div ref="chart3" class="chart-item"></div>
      
      <!-- 血压图表 -->
      <div ref="chart4" class="chart-item"></div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, onBeforeUnmount } from 'vue';
  import * as echarts from 'echarts';
  import { queryIndicator } from '@/api/Indicator';
  
  // 图表DOM引用
  const chart1 = ref(null);
  const chart2 = ref(null);
  const chart3 = ref(null);
  const chart4 = ref(null);
  
  // 图表实例存储
  const chartInstances = {
    chart1: null,
    chart2: null,
    chart3: null,
    chart4: null
  };
  
  // 统一数据处理
  const processData = (records) => {
    const sortedData = [...records]
      .sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
      .slice(0, 8)
      .reverse();
  
    return {
      dates: sortedData.map(item => 
        new Date(item.createdAt).toLocaleDateString('zh-CN')
      ),
      series: {
        height: sortedData.map(i => i.height),
        weight: sortedData.map(i => i.weight),
        bloodOxygen: sortedData.map(i => i.bloodOxygen),
        heartRate: sortedData.map(i => i.heartRate),
        bmi: sortedData.map(i => i.bmi),
        bloodGlucose: sortedData.map(i => i.bloodGlucose),
        bloodPressure: sortedData.map(i => ({
          systolic: parseInt(i.bloodPressure.split('/')[0]),
          diastolic: parseInt(i.bloodPressure.split('/')[1])
        }))
      }
    };
  };
  
  // 图表1：身高
  const initChart1 = (data) => {
    chartInstances.chart1 = echarts.init(chart1.value);
    chartInstances.chart1.setOption({
      title: { text: '身高变化趋势', left: 'center' },
      tooltip: { trigger: 'axis' },
      xAxis: { data: data.dates },
      yAxis: { name: '身高 (cm)' },
      series: [{
        name: '身高',
        type: 'line',
        data: data.series.height,
        smooth: true,
        itemStyle: { color: '#5470C6' }
      }]
    });
  };
  
  // 图表2：体重/血氧/心率
  const initChart2 = (data) => {
    chartInstances.chart2 = echarts.init(chart2.value);
    chartInstances.chart2.setOption({
      title: { text: '体重/血氧/心率趋势', left: 'center' },
      tooltip: { trigger: 'axis' },
      legend: { data: ['体重', '血氧', '心率'], top: 30 },
      xAxis: { data: data.dates },
      yAxis: [
        { name: '体重 (kg)', position: 'left' },
        { name: '血氧 (%)', position: 'right' },
        { name: '心率 (bpm)', position: 'right', offset: 30 }
      ],
      series: [
        {
          name: '体重',
          type: 'line',
          yAxisIndex: 0,
          data: data.series.weight,
          itemStyle: { color: '#91CC75' }
        },
        {
          name: '血氧',
          type: 'line',
          yAxisIndex: 1,
          data: data.series.bloodOxygen,
          itemStyle: { color: '#EE6666' }
        },
        {
          name: '心率',
          type: 'line',
          yAxisIndex: 2,
          data: data.series.heartRate,
          itemStyle: { color: '#FAC858' }
        }
      ]
    });
  };
  
  // 图表3：BMI/血糖
  const initChart3 = (data) => {
    chartInstances.chart3 = echarts.init(chart3.value);
    chartInstances.chart3.setOption({
      title: { text: 'BMI/血糖趋势', left: 'center' },
      tooltip: { trigger: 'axis' },
      legend: { data: ['BMI', '血糖'], top: 30 },
      xAxis: { data: data.dates },
      yAxis: [
        { name: 'BMI', position: 'left' },
        { name: '血糖 (mmol/L)', position: 'right' }
      ],
      series: [
        {
          name: 'BMI',
          type: 'line',
          yAxisIndex: 0,
          data: data.series.bmi,
          itemStyle: { color: '#73C0DE' }
        },
        {
          name: '血糖',
          type: 'line',
          yAxisIndex: 1,
          data: data.series.bloodGlucose,
          itemStyle: { color: '#3BA272' }
        }
      ]
    });
  };
  
  // 图表4：血压（双指标）
  const initChart4 = (data) => {
    chartInstances.chart4 = echarts.init(chart4.value);
    chartInstances.chart4.setOption({
      title: { text: '血压变化趋势', left: 'center' },
      tooltip: {
        trigger: 'axis',
        formatter: (params) => {
          const date = params[0].axisValue;
          const systolic = params[0].data;
          const diastolic = params[1].data;
          return `${date}<br>
            ${params[0].marker} 收缩压: ${systolic} mmHg<br>
            ${params[1].marker} 舒张压: ${diastolic} mmHg`;
        }
      },
      legend: { data: ['收缩压', '舒张压'], top: 30 },
      xAxis: { data: data.dates },
      yAxis: { name: '血压 (mmHg)' },
      series: [
        {
          name: '收缩压',
          type: 'line',
          data: data.series.bloodPressure.map(i => i.systolic),
          itemStyle: { color: '#FC8452' }
        },
        {
          name: '舒张压',
          type: 'line',
          data: data.series.bloodPressure.map(i => i.diastolic),
          itemStyle: { color: '#9A60B4' }
        }
      ]
    });
  };
  
  // 统一获取数据
  const fetchData = async () => {
    try {
      const params = {
        userId: parseInt(localStorage.getItem('aimid')),
        startDate: "2000-01-01",
        endDate: "3000-01-01",
        pageIndex: 0,
        pageSize: 10
      };
  
      const { code, data } = await queryIndicator(params);
      if (code === '000') {
        const processed = processData(data.records);
        initChart1(processed);
        initChart2(processed);
        initChart3(processed);
        initChart4(processed);
      }
    } catch (error) {
      console.error('数据获取失败:', error);
    }
  };
  
  // 响应式调整
  const handleResize = () => {
    Object.values(chartInstances).forEach(instance => instance?.resize());
  };
  
  onMounted(() => {
    fetchData();
    window.addEventListener('resize', handleResize);
  });
  
  onBeforeUnmount(() => {
    window.removeEventListener('resize', handleResize);
    Object.values(chartInstances).forEach(instance => instance?.dispose());
  });
  </script>
  
  <style scoped>
  .dashboard {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
    padding: 20px;
  }
  
  .chart-item {
    height: 400px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.1);
    padding: 15px;
  }
  
  @media (max-width: 768px) {
    .dashboard {
      grid-template-columns: 1fr;
    }
  }
  </style>